﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Data;
using NHibernate.Cfg;
using FluentNHibernate.Cfg;
using log4net;
using FluentNHibernate.Automapping;
using System.Reflection;
using HotelCommon.Models;

namespace HotelDAO.DAO
{
    /// <summary>
    /// Session factory for HotelDAO
    /// </summary>
    public class HotelDAOSessionFactory
    {

        private static ILog mLog = LogManager.GetLogger(typeof(HotelDAOSessionFactory));
        /// <summary>
        /// Session factory instance
        /// </summary>
        public static ISessionFactory SessionFactory { get; set; }

        public static void Start()
        {
            mLog.Debug("Start <--- enter");
            var cfg = new Configuration();
            SessionFactory = Fluently.Configure(cfg)
                .Mappings(m =>
                    {
                        m.FluentMappings.AddFromAssemblyOf<HotelDAO>();
                        m.HbmMappings.AddFromAssemblyOf<HotelDAO>();
                    })
                .BuildSessionFactory();
            mLog.Debug("Start ---> leave");
        }

        public static ISession OpenSession()
        {
            var session = SessionFactory.OpenSession();
            try
            {
                var connectionState = session.Connection.State;
                if (connectionState == ConnectionState.Closed || connectionState == ConnectionState.Broken)
                {
                    session.Reconnect();
                }
            }
            catch (Exception)
            {
                // do nothing
            }
            return session;
        }

        /// <summary>
        /// Open stateless session.
        /// </summary>
        /// <returns></returns>
        public static IStatelessSession OpenStatelessSession<T>()
        {
            var statelessSession = SessionFactory.OpenStatelessSession();
            try
            {
                var connectionState = statelessSession.Connection.State;
                if (connectionState == ConnectionState.Closed || connectionState == ConnectionState.Broken)
                {
                    statelessSession.Connection.Open();
                }
            }
            catch (Exception)
            {
                // do nothing
            }
            return statelessSession;
        }
    }
}
